package com.farm.pic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.farm.baiduapi.Base64Util;
import com.farm.baiduapi.FileUtil;
import com.farm.common.RequestMessage;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: Pic
 * Package: com.farm.pic
 * Description
 *
 * @Author KarUo
 * @Create 2024/3/9 20:47
 * @Version 1.0
 */
@Slf4j
public class Pic {
    private final String ACCESS_TOKEN_URI = "https://aip.baidubce.com/oauth/2.0/token";
    private final String CHAT_URI = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";

    private String apiKey = "Cjpbv2pCdCIv3HjjMcMjf3qy";
    private String secretKey = "xobhsptDyldjmXU55ERmlkd3X4oP6czF";
    private String accessToken = "";

    private OkHttpClient client ;

    //请求参数
    private RequestMessage requestBody = new RequestMessage();
    //响应超时时间
    private int responseTimeOut = 5000;

    public Pic(){
        this.client = new OkHttpClient.Builder().readTimeout(responseTimeOut, TimeUnit.SECONDS).build();
    }

    public Pic(int responseTimeOut){
        this.client = new OkHttpClient.Builder().readTimeout(responseTimeOut,TimeUnit.SECONDS).build();
    }

    public boolean getAccessToken(){
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        //创建一个请求
        Request request = new Request.Builder()
                .url(ACCESS_TOKEN_URI+"?client_id=" + apiKey + "&client_secret=" + secretKey + "&grant_type=client_credentials")
                .method("POST",body)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            //使用浏览器对象发起请求
            Response response = client.newCall(request).execute();
            //只能执行一次response.body().string()。下次再执行会抛出流关闭异常，因此需要一个对象存储返回结果
            String responseMessage = response.body().string();
            log.debug("获取accessToken成功");
            JSONObject jsonObject = JSON.parseObject(responseMessage);
            accessToken = (String) jsonObject.get("access_token");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     * 获取图片地址参数，返回答案
     * @param path
     */
    public String getAnswer(String path) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\OIP-C.jpg") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        String image=getFileContentAsBase64(path,true);
        String image1= "image=" + image;//凭借此语句转换到正确格式，负责会报错216101
        RequestBody body = RequestBody.create(mediaType, image1);
        Request request = new Request.Builder()
                .url(CHAT_URI + "?access_token="+accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
       String filePath=path;
        byte[] b = FileUtil.readFileByBytes(filePath);
        String base64 = Base64Util.encode(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


}
